package com.bugpool.leilema.tc.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.api.R;
import com.bugpool.leilema.freamwork.datascope.DataScopeConstants;
import com.bugpool.leilema.freamwork.exception.APIException;
import com.bugpool.leilema.freamwork.satoken.SaTokenUtil;
import com.bugpool.leilema.tc.bean.entity.SysRole;
import com.bugpool.leilema.tc.bean.entity.SysUser;
import com.bugpool.leilema.tc.bean.enums.StatusEnum;
import com.bugpool.leilema.tc.bean.interfaces.UserConvert;
import com.bugpool.leilema.tc.bean.req.LoginReq;
import com.bugpool.leilema.tc.bean.vo.SysUserVo;
import com.bugpool.leilema.tc.mapper.RoleDeptMapper;
import com.bugpool.leilema.tc.mapper.RoleMapper;
import com.bugpool.leilema.tc.mapper.UserMapper;
import com.bugpool.leilema.tc.mapper.UserRoleMapper;
import com.bugpool.leilema.tc.service.LoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @Author wh
 * @Description
 * @Date 2023/3/1 14:47
 * @Version 1.0
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleDeptMapper roleDeptMapper;

    @Override
    public SaTokenInfo login(LoginReq loginReq) {
        SysUser login = userMapper.login(loginReq);
        //判断用户角色是否禁用
        if (login != null) {
            StpUtil.login(login.getUserId());
            //判断状态是否正常
            if (StatusEnum.DISABLE == StatusEnum.getStatusEnum(login.getStatus())) {
                throw new RuntimeException("账号已被禁用");
            }
            //根据用户id 获取 角色权限id集合
            List<Long> roleIds = userRoleMapper.getRoleIdsByUserId(login.getUserId());
            // 对象转换
            SysUserVo sysUserVo = UserConvert.INSTANCE.sysUserToUserVo(login);

            //根据角色id集合 求出 数据权限部门id
            if (CollUtil.isEmpty(roleIds)) {

            } else {
                //根据 角色id 算出部门id集合
                List<SysRole> roles = roleMapper.getRolesByRoleIds(roleIds);
//                roles.stream().filter(role -> role.getDataScope().equals(DataScopeConstants.DATA_SCOPE_ALL)).forEach(role -> {
//                    sysUserVo.setAdmin(true);
//                });
                sysUserVo.setSysRoleList(roles);
                sysUserVo.setRoleIds(roleIds);
            }
            SaTokenUtil.setUser(sysUserVo);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return tokenInfo;
        }
        throw new RuntimeException("账号或密码错误请重新输入");
    }


}
